<?php
/*
License:
	MIT-style license

Author:
	Jan Kassens

Note:
	magic_quotes_gpc needs to be turned off.
*/
require 'mooresponse.php';
class MooRemote{

	private $functions = array();

	private $options;

	public function __construct($options = array()){
		$this->options = $options;
	}

	public function error($errno, $errstr){
		echo MooResponse::error($errstr);
		exit;
	}

	public function getJavascript($tag = true){
		$return = "var mooRemote=new MooRemote(" . json_encode($this->functions);
		if(count($this->options) > 0) $return .= "," . json_encode($this->options);
		$return .= ");";
		if($tag) $return = "<script type=\"text/javascript\">$return</script>";
		return $return;
	}

	public function processRequest($exit = true){
		if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) || $_SERVER['HTTP_X_REQUESTED_WITH'] != 'MooRequest') return;
		set_error_handler(array($this, 'error'), E_ALL);
		try {
			list($function, $params) = json_decode($_POST['call'], true);
			if(!in_array($function, $this->functions)) throw new Exception('Invalid request.');
			if(!is_callable($function, false, $callable)) throw new Exception("'$callable' is not callable.");
			$response = call_user_func_array($function, $params);
			if(!($response instanceof MooResponse)) $response = MooResponse::arguments($response);
			echo $response;
		} catch (Exception $e) {
			$this->error(1, $e->getMessage());
		}
		restore_error_handler();
		if($exit) exit;
	}

	public function registerFunction($callback){
		$this->functions[] = $callback;
	}

}
?>